package com.example.tools;

import java.math.BigDecimal;

/**
 * Created by studio on 2017/5/12.
 */
public class Uniqid {

    /*
    * 目前只有13位，需精确到16位才能做到跟PHP的uniqid一样
    * 理论上这个只能做到1秒生成1000个，而php是1秒生成 10^6 个  (´・ω・`)
    * 然而去请求http调用php接口生成uniqid..不造是否能做到在这里1微秒生成一个?
    */
    public synchronized static String getId(){

        long now = System.currentTimeMillis();

        BigDecimal part1 = BigDecimal.valueOf(now/1000);
        BigDecimal time = BigDecimal.valueOf(now).divide(BigDecimal.valueOf(1000));
        BigDecimal part2 = time.subtract(part1).multiply(BigDecimal.valueOf(1000000));

        String hex1 = Integer.toHexString(part1.intValue());
        String hex2 = Integer.toHexString(part2.intValue());

        while (hex2.length() < 5){
            hex2 = '0'+hex2;
        }

        try {
            Thread.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return hex1.substring(0,8)+hex2.substring(0,5);
    }
}
